From e359a7a3c4f9e70360a068bef19c95938fdacede Mon Sep 17 00:00:00 2001
From: Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
Date: Wed, 23 Dec 2015 11:33:14 +0100
Subject: [PATCH] Adjust library/header paths for cross-compilation

When cross-compiling third-party extensions, the get_python_inc() or
get_python_lib() can be called, to return the path to headers or
libraries. However, they use the sys.prefix of the host Python, which
returns incorrect paths when cross-compiling (paths pointing to host
headers and libraries).

In order to fix this, we introduce the _python_sysroot, _python_prefix
and _python_exec_prefix variables, that allow to override these
values, and get correct header/library paths when cross-compiling
third-party Python modules.

Signed-off-by: Thomas Petazzoni <thomas.petazzoni@free-electrons.com>
---
 Lib/distutils/command/build_ext.py |  5 ++++-
 Lib/sysconfig.py                   | 15 +++++++++++----
 2 files changed, 15 insertions(+), 5 deletions(-)

--- a/Lib/distutils/command/build_ext.py
+++ b/Lib/distutils/command/build_ext.py
@@ -234,7 +234,10 @@ class build_ext(Command):
         if (sysconfig.get_config_var('Py_ENABLE_SHARED')):
             if not sysconfig.python_build:
                 # building third party extensions
-                self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
+                libdir = sysconfig.get_config_var('LIBDIR')
+                if "_python_sysroot" in os.environ:
+                    libdir = os.environ.get("_python_sysroot") + libdir
+                self.library_dirs.append(libdir)
             else:
                 # building python standard extensions
                 self.library_dirs.append('.')
--- a/Lib/sysconfig.py
+++ b/Lib/sysconfig.py
@@ -168,10 +168,17 @@ _SCHEME_KEYS = ('stdlib', 'platstdlib',
 _PY_VERSION = sys.version.split()[0]
 _PY_VERSION_SHORT = f'{sys.version_info[0]}.{sys.version_info[1]}'
 _PY_VERSION_SHORT_NO_DOT = f'{sys.version_info[0]}{sys.version_info[1]}'
-_PREFIX = os.path.normpath(sys.prefix)
-_BASE_PREFIX = os.path.normpath(sys.base_prefix)
-_EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
-_BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
+if "_python_sysroot" in os.environ:
+    _sysroot=os.environ.get('_python_sysroot')
+    _PREFIX = os.path.normpath(_sysroot + os.environ.get('_python_prefix'))
+    _EXEC_PREFIX = os.path.normpath(_sysroot + os.environ.get('_python_exec_prefix'))
+    _BASE_PREFIX = _PREFIX
+    _BASE_EXEC_PREFIX = _EXEC_PREFIX
+else:
+    _PREFIX = os.path.normpath(sys.prefix)
+    _EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
+    _BASE_PREFIX = os.path.normpath(sys.base_prefix)
+    _BASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)
 _CONFIG_VARS = None
 _USER_BASE = None
 
